package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Food;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.FoodService;
import com.itheima.utils.POIUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/food")
public class FoodController {
    @Reference
    private FoodService foodService;

    //文件上传功能
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //读取excle数据,表格数据转换为List
            List<String[]> readExcel = POIUtils.readExcel(excelFile);
            if (readExcel != null && readExcel.size() > 0) {
                ArrayList<Food> foodList = new ArrayList<>();
                for (int i = 0; i < readExcel.size(); i++) {
                    String[] strings = readExcel.get(i);

                    Food food = new Food(strings[0], strings[1], strings[2], strings[3]);
                    foodList.add(food);
                }
                foodService.add(foodList);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_FOOD_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_FOOD_SUCCESS);

    }

    //分页查询功能
    @RequestMapping("/findByPage")
    public PageResult findByPage(@RequestBody QueryPageBean queryPageBean) {
        return foodService.findByPage(queryPageBean);
    }
    //报表导出来 进行编辑修改操作
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response,Integer pageSize,  Integer currentPage, String queryString) {
        try {
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "food_template.xls";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            HSSFWorkbook excel = new HSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            HSSFSheet sheet = excel.getSheetAt(0);
            queryString = URLDecoder.decode(queryString, "utf-8");

            QueryPageBean queryPageBean = new QueryPageBean(currentPage,pageSize,queryString);
            //获取当前页的数据
            List<Food> foodList = foodService.findCurrentPage(queryPageBean);
            int rowNum = 1;
            for (Food food : foodList) {
                String foodName = food.getFoodName();
                String foodTip = food.getFoodTip();
                String foodUnit = food.getFoodUnit();
                String age = food.getAge();

                HSSFRow row = sheet.getRow(rowNum++);
                row.getCell(0).setCellValue(foodName);//食物名称
                row.getCell(1).setCellValue(foodTip);//食物说明
                row.getCell(2).setCellValue(foodUnit);//用食规格
                row.getCell(3).setCellValue(age);//使用年龄

            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=food_t.xls");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_FOOD_REPORT_FAIL);

        }

    }

    //根据id删除功能
    @RequestMapping("/deleteById")
    public Result deleteById(Integer id) {
        try {
           foodService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            //当添加失败时,捕获异常,并返回Result
            return new Result(false, MessageConstant.DELETE_FOOD_FAIL);
        }
        //添加成功后返回Result
        return new Result(true, MessageConstant.DELETE_FOOD_SUCCESS);
    }

    ///查询所有膳食信息
    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<Food> exerciseList = foodService.findAll();
            return new Result(true,MessageConstant.GET_FOOD_LIST_SUCCESS,exerciseList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_FOOD_LIST_FAIL);
        }
    }
}


